# -*-coding:utf-8-*-

import json
import time
from datetime import timedelta
from pyrestful import mediatypes
from pyrestful.rest import post
from handlers.base import BaseHandler
from tornado.gen import coroutine
from tornado.httpclient import AsyncHTTPClient, HTTPRequest


class SpecDevicesHandler(BaseHandler):
    def __init__(self, application, request, **kwargs):
        super(SpecDevicesHandler, self).__init__(application, request, **kwargs)

    @post(_path='/spec/api/devices/paid', _types=[dict],
          _consumes=mediatypes.APPLICATION_JSON)
    @coroutine
    def devices_on_paid(self, request):
        device_id = request['device_id']
        result = json.dumps(request)
        topic = 't/d/%s/n/paid' % device_id
        self.mqtornado.publish(topic, result)
    
    @post(_path='/spec/api/devices/recharge', _types=[dict],
          _consumes=mediatypes.APPLICATION_JSON)
    @coroutine
    def devices_on_recharge(self, request):
        device_id = request['device_id']
        recharge_days = int(request['recharge_days'])
        # TODO: check auth key
        recharge_seconds = int(timedelta(days=recharge_days).total_seconds())
        cur_time = int(time.time())

        # TODO: 考虑安全性
        # TODO: 考虑多进程并发情况/ZK LOCK

        # TODO: 使用 PUT /platform/devices/{did}/specifics/{field}　接口
        # TODO: 将 mqtt 推送实现于 delegate 中

        # if self.prod:
        #     url = 'http://iot1.hifocus.top/internal/api/devices/%s/specifics/wpm_quota' % device_id
        # else:
        #     url = 'http://localhost:18600/internal/api/devices/%s/specifics/wpm_quota' % device_id
        # http_request = HTTPRequest(url, method='PUT', body=json.dumps(request))
        # http_client = AsyncHTTPClient()
        # response = yield http_client.fetch(http_request, raise_error=False)

        filter_cond = {'device_id': device_id}
        result = yield self.devices_dao.find_one(filter_cond, {'specifics': 1})
        if result is not None and 'specifics' in result:
            if 'wpm_quota' in result['specifics']:
                wpm_quota = result['specifics']['wpm_quota']
                if 'expire_time' in wpm_quota and wpm_quota['expire_time'] > cur_time:
                    wpm_quota['expire_time'] += recharge_seconds
                else:
                    wpm_quota['expire_time'] = cur_time + recharge_seconds
            else:
                wpm_quota = {
                    'expire_time': cur_time + recharge_seconds,
                }
        else:
            wpm_quota = {
                'expire_time': cur_time + recharge_seconds,
            }
        wpm_quota['mode'] = 4

        self.logger.debug(wpm_quota)

        yield self.devices_dao.update_one(filter_cond, {'$set': {'specifics.wpm_quota': wpm_quota}}, upsert=True)

        # publish to message queue
        result = {
            'mode': wpm_quota['mode'],
        }
        if 4 == result['mode']:  # 按时间
            remain = int(wpm_quota['expire_time']) - int(time.time())
            if 0 >= remain:
                result['exceeded'] = 1
            else:
                result['exceeded'] = 0
                result['remain'] = remain
        elif 8 == result['mode']:  # 按流量
            remain = int(wpm_quota['remain']) - int(wpm_quota['used'])
            if 0 >= remain:
                result['exceeded'] = 1
            else:
                result['exceeded'] = 0
                result['remain'] = remain

        result = json.dumps(result)
        topic = 't/d/%s/n/wpm_quota' % device_id
        self.mqtornado.publish(topic, result)
